// pages/myCarte/myCarte.js
import { baseUrl, ftp_share_image, get_carte, get_carte_count, update_scan } from "../../utils/api.js";

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareContent: '',
    btuBottom: 0,
    TaskShow: 0, //默认0 ，用户授权 1 ，分享 2
    haveTap: 1, // 1: 可以点击 0：不可点击
    haveShare: 0, // 0：完成/未开始 1：分享
    OrderCount: [
      {
        name: '订单列表',
        content: '',
        img_src: '../../images2/hou_ddan.svg',
        url: '../../shopPages/OrderList/OrderList'
      },
      {
        name: '系统销售',
        content: '',
        img_src: '../../images2/hou_mp.svg',
        url: '../../shopPages/cardSales/cardSales'
      },
      {
        name: '安全档案',
        content: '',
        img_src: '../../images2/hou_anq.svg',
        url: '../../shopPages/archives/archives'
      },
      {
        name: '积分详情',
        content: '',
        img_src: '../../images2/hou_jifen.svg',
        url: '../../shopPages/houIntegral/houIntegral',
      },
    ],
    TodayCount: [{
      name: '今日浏览',
      content: ''
    },
    {
      name: '今日收藏',
      content: ''
    },
    {
      name: '今日点赞',
      content: ''
    },
    {
      name: '今日推荐',
      content: ''
    }
    ],
    TotalCount: [{
      name: '浏览总数',
      content: ''
    },
    {
      name: '收藏总数',
      content: ''
    },
    {
      name: '点赞总数',
      content: ''
    },
    {
      name: '推荐总数',
      content: ''
    }
    ],
    content: '',
    unreadnum: 0,
    unreadnum2: 0,
    share_img: {
      type: 0,
      src: '../../images/img_block.png'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getSystemInfo({
      success: res => {
        // console.log('手机信息res'+res.model)
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1) {
          that.setData({
            btuBottom: '42rpx'
          });
        }
      }
    })

    this.getCarteInfo(app.globalData.userInfo.id, app.globalData.userInfo.id)

    var url2 = '/log_api/logReadNum';
    var params2 = {
      uid: app.globalData.userInfo.id
    };
    app.HttpGetSend(url2, params2, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        var count = res.data;
        if (count > 99) {
          count = 99;
        }
        that.setData({
          unreadnum: count
        })
      }
    });

    var url3 = '/chat_api/getReadNum';
    var params3 = {
      uid: app.globalData.userInfo.id
    };
    app.HttpGetSend(url3, params3, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        var count = res.data;
        if (count > 99) {
          count = 99;
        }
        that.setData({
          unreadnum2: count
        })
      }
    });

    var url21 = "/cardshop_api/card_word";
    var params21 = {
      type: 3,
      uid: app.globalData.userInfo.id
    }
    app.HttpPostSend(url21, params21,
      function (result_data) {

        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {
          if (!!result_data.data) {
            that.setData({
              shareContent: result_data.data.content
            })
          }
        }
      })
  },
  no_share: function () {
    wx.showModal({
      title: '提示',
      content: '名片信息未审核，请联系客服',
    })
  },
  // 获取名片信息
  getCarteInfo: function (uid, v_id) {
    const that = this
    app.HttpGetSend(
      get_carte, {
        uid: uid,
        v_id: v_id
      },
      function (res) {
        // console.log(res)
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          app.globalData.userInfo = { ...res.data }
          that.setData({
            userInfo: {
              ...res.data
            }
          })
          let checkNullEmpty = (aim) => {
            if (aim != '' && aim != null) {
              return true
            } else {
              return false
            }
          }
          // 名片信息
          let CarteInfo = new Object()
          CarteInfo.id = res.data.id
          CarteInfo.is_staff = res.data.is_staff
          CarteInfo.examine_status = res.data.examine_status
          CarteInfo.is_allow = res.data.is_allow
          // 名片 形象照
          CarteInfo.img = new Object()
          CarteInfo.img = {
            type: 0,
            src: '../../images/img_block.png'
          }
          if (checkNullEmpty(res.data.img)) {
            CarteInfo.img = {
              type: 1,
              src: res.data.img
            }
          }
          // 名片 分享图
          if (checkNullEmpty(res.data.share_img)) {
            that.setData({
              share_img: {
                type: 1,
                src: res.data.share_img
              }
            })
          }
          // 名片 公司名
          CarteInfo.comName = new Object()
          CarteInfo.comName = {
            type: 0,
            content: '公司'
          }
          if (checkNullEmpty(res.data.company)) {
            CarteInfo.comName = {
              type: 1,
              content: res.data.company
            }
          }
          // 名片 公司logo
          CarteInfo.comLogo = new Object()
          CarteInfo.comLogo = {
            type: 0,
            src: '../../images/carteFavorites/logo_block.png'
          }
          if (checkNullEmpty(res.data.com_logo)) {
            CarteInfo.comLogo = {
              type: 1,
              src: res.data.com_logo
            }
          }
          // 名片 职业
          CarteInfo.position = new Object()
          CarteInfo.position = {
            type: 0,
            content: '职业'
          }
          if (checkNullEmpty(res.data.position)) {
            CarteInfo.position = {
              type: 1,
              content: res.data.position
            }
          }
          // 名片 名字
          CarteInfo.name = new Object()
          CarteInfo.name = {
            type: 0,
            content: '名字'
          }
          if (checkNullEmpty(res.data.name)) {
            CarteInfo.name = {
              type: 1,
              content: res.data.name
            }
          }
          // 名片 手机号
          CarteInfo.mobile = new Object()
          CarteInfo.mobile = {
            type: 0,
            content: '手机号'
          }
          if (checkNullEmpty(res.data.mobile)) {
            CarteInfo.mobile = {
              type: 1,
              content: res.data.mobile
            }
          }
          // 名片 邮箱
          CarteInfo.email = new Object()
          CarteInfo.email = {
            type: 0,
            content: '邮箱'
          }
          if (checkNullEmpty(res.data.email)) {
            CarteInfo.email = {
              type: 1,
              content: res.data.email
            }
          }
          // 名片 地址
          CarteInfo.address = new Object()
          CarteInfo.address = {
            type: 0,
            content: '地址'
          }
          if (checkNullEmpty(res.data.address)) {
            CarteInfo.address = {
              type: 1,
              content: res.data.address
            }
          }
          that.setData({
            CarteInfo
          })
          wx.setStorage({
            key: 'userInfo',
            data: JSON.stringify({
              ...res.data
            })
          })
          that.getCarteCount(res.data.id)
        }
      })
  },

  // 获取名片数据统计
  getCarteCount: function (id) {
    const that = this
    app.HttpPostSend(
      get_carte_count, {
        uid: id
      },
      function (res) {
        // console.log(res)
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          let TodayCount = [...that.data.TodayCount]
          TodayCount[0].content = res.data[0].browse
          TodayCount[1].content = res.data[0].collection
          TodayCount[2].content = res.data[0].point
          TodayCount[3].content = res.data[0].invite
          let TotalCount = [...that.data.TotalCount]
          TotalCount[0].content = res.data[1].browse
          TotalCount[1].content = res.data[1].collection
          TotalCount[2].content = res.data[1].point
          TotalCount[3].content = res.data[1].invite
          let OrderCount = [...that.data.OrderCount]
          OrderCount[0].content = res.data[2].deliver
          OrderCount[1].content = res.data[2].after
          that.setData({
            TodayCount,
            TotalCount,
            OrderCount
          })
        }
      })
  },

  // 进入名片详情页
  showCarte: function (e) {
    // console.log(e)
    const that = this
    const haveTap = this.data.haveTap
    const userInfo = this.data.userInfo
    if (haveTap == 0) {
      console.log('屏蔽重复点击')
    } else {
      that.setData({
        haveTap: 0
      })
      // this.renderCanvasCarte(0, this.data.CarteList[0])
      app.HttpGetSend(
        update_scan, {
          uid: userInfo.id,
          browse_id: userInfo.id
        },
        function (res) {
          // console.log(res)
          if (res.msg != "success") {
            app.showTipMsg(res.msg);
          } else {
            app.globalData.SwitchTabParams = {
              v_id: userInfo.id
            }
            that.setData({
              haveTap: 1
            })
            wx.switchTab({
              url: '/pages/carteShow/carteShow'
            })
          }
        })
    }
  },

  // 名片canvas渲染并打开分享遮罩层
  canvasAndShowshare: function () {
    const that = this
    const CarteInfo = this.data.CarteInfo
    if (that.data.userInfo.id == CarteInfo.id && that.data.userInfo.type == 1) {
      app.showTipMsg('无权限');
      return false;
    }

    var url2 = "/cardshop_api/card_word";
    var params2 = {
      type: 3,
      uid: CarteInfo.id
    }
    app.HttpPostSend(url2, params2,
      function (result_data) {
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {
          if (!!result_data.data) {
            that.setData({
              content: result_data.data.content
            })
          }
        }
      })

    const userInfo = this.data.userInfo
    this.setData({
      haveTap: 0,
      haveShare: 0,
    })
    // wx.showLoading({
    //   mask: 'true'
    // })
    wx.hideTabBar()
    // wx.hideLoading()
    this.setData({
      haveTap: 1,
      haveShare: 1,
      TaskShow: 2,
      shareInfo: {
        carte: CarteInfo,
        share_id: userInfo.id
      }
    })
    // that.renderCanvasCarte(CarteInfo).then(render_canvas_res => {
    //   // console.log(render_canvas_res)
    //   wx.hideTabBar()
    //   wx.hideLoading()
    //   that.setData({
    //     haveTap: 1,
    //     haveShare: 1,
    //     TaskShow: 2,
    //     shareInfo: {
    //       carte: CarteInfo,
    //       share_id: userInfo.id,
    //       share_img: render_canvas_res
    //     }
    //   })
    // })
  },

  // canvas渲染
  renderCanvasCarte: function (params) {
    const that = this
    // console.log(params)
    // const params = this.data.CarteList[idx]
    const wxGetImageInfo = function (src) {
      let p = new Promise((resolve, reject) => {
        // console.log(server_url + uri)
        wx.getImageInfo({
          src: src,
          success(res) {
            resolve(res)
          },
          fail(err) {
            reject(err)
          },
          complete() {

          }
        })
      })
      return p
    }
    const weGetElementInfo = function (filterArr) {
      let p = new Promise((resolve, reject) => {
        // console.log(server_url + uri)
        const query = wx.createSelectorQuery()
        filterArr.map(items => {
          if (items.type == 1) {
            return query.select(items.content).boundingClientRect()
          } else if (items.type == 2) {
            return query.selectAll(items.content).boundingClientRect()
          }
        })
        query.exec(result => {
          resolve(result)
        })
      })
      return p
    }
    const toTempPath = new Promise((resolve, reject) => {
      Promise.all([
        weGetElementInfo([{
          content: '.carte_mainBox',
          type: 1
        },
        {
          content: '.carte_mainBox .mainLeft .avatar',
          type: 1
        }, //用户形像照
        {
          content: '.carte_mainBox .mainLeft .avatarMask',
          type: 1
        }, //头像遮罩
        {
          content: '.carte_mainBox .mainRight .companyInfo .company',
          type: 1
        }, //公司名称
        {
          content: '.carte_mainBox .mainRight .companyInfo .logo',
          type: 1
        }, //公司logo
        {
          content: '.carte_mainBox .mainRight .positionInfo2 .job',
          type: 1
        }, //职位
        {
          content: '.carte_mainBox .mainRight .positionInfo2 .point',
          type: 1
        }, //点
        {
          content: '.carte_mainBox .mainRight .positionInfo .name',
          type: 1
        }, //名字
        {
          content: '.carte_mainBox .mainRight .phoneInfo .phone',
          type: 1
        }, //电话
        {
          content: '.carte_mainBox .mainRight .phoneInfo .icon',
          type: 1
        }, //电话Icon
        {
          content: '.carte_mainBox .mainRight .mailInfo .mail',
          type: 1
        }, //邮箱
        {
          content: '.carte_mainBox .mainRight .mailInfo .icon',
          type: 1
        }, //邮箱Icon
        {
          content: '.carte_mainBox .mainRight .addrInfo .addr',
          type: 1
        }, //地址
        {
          content: '.carte_mainBox .mainRight .addrInfo .icon',
          type: 1
        }, //地址Icon
        ]),
        wxGetImageInfo(params.img.src),
        wxGetImageInfo(params.comLogo.src),
      ]).then(res => {
        // console.log(res)
        let topBorder = res[0][0].top
        let leftBorder = res[0][0].left
        let canvasWidth = res[0][0].width
        let canvasHeight = res[0][0].height
        let getPosition = (type, index) => {
          let aimTop = res[0][index].top - topBorder
          let aimLeft = res[0][index].left - leftBorder
          if (type == 0 || type == 3) {
            return [aimLeft, aimTop]
          } else if (type == 1) {
            return [res[0][index].width, res[0][index].height]
          } else if (type == 2) {
            return [aimLeft, aimTop, res[0][index].width, res[0][index].height]
          }
        }
        let roundRect = (ctx_ctx, x, y, w, h, r) => {
          ctx_ctx.save()

          // 开始绘制
          ctx_ctx.beginPath()
          // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
          // 这里是使用 fill 还是 stroke都可以，二选一即可
          ctx_ctx.setFillStyle('transparent')
          // ctx_ctx.setStrokeStyle('transparent')
          // 左上角
          ctx_ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

          // border-top
          ctx_ctx.moveTo(x + r, y)
          ctx_ctx.lineTo(x + w - r, y)
          ctx_ctx.lineTo(x + w, y + r)
          // 右上角
          ctx_ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

          // border-right
          ctx_ctx.lineTo(x + w, y + h - r)
          ctx_ctx.lineTo(x + w - r, y + h)
          // 右下角
          ctx_ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

          // border-bottom
          ctx_ctx.lineTo(x + r, y + h)
          ctx_ctx.lineTo(x, y + h - r)
          // 左下角
          ctx_ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

          // border-left
          ctx_ctx.lineTo(x, y + r)
          ctx_ctx.lineTo(x + r, y)

          // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
          ctx_ctx.fill()
          // ctx_ctx.stroke()
          ctx_ctx.closePath()
          // 剪切
          ctx_ctx.clip()

          ctx_ctx.restore()
        }
        const ctx = wx.createCanvasContext('carte_canvas')

        // 白色背景
        ctx.rect(0, 0, canvasWidth, canvasHeight)
        ctx.setFillStyle('white')
        ctx.fill()

        // roundRect(ctx,0,0,canvasWidth,canvasHeight,10)

        // 个人形象照
        ctx.drawImage(res[1].path, ...getPosition(2, 1))

        // 形象照遮挡
        ctx.drawImage('../../images/carteShow/avatar_fg.png', ...getPosition(2, 2))

        // 公司名称
        ctx.setFontSize(11)
        ctx.fillStyle = '#333'
        ctx.setTextBaseline('top')
        ctx.fillText(params.comName.content, ...getPosition(0, 3))

        // 公司LOGO
        ctx.drawImage(res[2].path, ...getPosition(2, 4))

        // 职位
        ctx.setFontSize(12)
        ctx.fillStyle = '#333'
        ctx.setTextBaseline('top')
        ctx.fillText(params.position.content, ...getPosition(0, 5))

        // 点
        // console.log(...getPosition(2, 6))
        ctx.beginPath()
        ctx.rect(...getPosition(2, 6))
        ctx.setFillStyle('#333')
        ctx.fill()

        // 名字
        ctx.setFontSize(24)
        ctx.fillStyle = '#333';
        ctx.fillText(params.name.content, ...getPosition(0, 7))

        // 电话
        ctx.setFontSize(10)
        ctx.fillStyle = '#333';
        ctx.fillText(params.mobile.content, ...getPosition(0, 8))

        // 电话Icon
        ctx.drawImage('../../images/carteShow/phone.png', ...getPosition(2, 9))

        // 邮箱
        ctx.setFontSize(10)
        ctx.fillStyle = '#333';
        ctx.fillText(params.email.content, ...getPosition(0, 10))

        // 邮箱Icon
        ctx.drawImage('../../images/carteShow/email.png', ...getPosition(2, 11))

        // 地址
        ctx.setFontSize(10)
        ctx.fillStyle = '#333';
        ctx.fillText(params.address.content, ...getPosition(0, 12))

        // 地址Icon
        ctx.drawImage('../../images/carteShow/addr.png', ...getPosition(2, 13))

        ctx.draw(false, function (canvas_res) {
          // console.log(canvas_res)
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 500,
            height: 400,
            destWidth: 500,
            destHeight: 400,
            canvasId: 'carte_canvas',
            success(canvas_temp_res) {
              // resolve(canvas_temp_res.tempFilePath)
              // console.log(canvas_temp_res)
              wx.uploadFile({
                url: baseUrl + ftp_share_image, // 仅为示例，非真实的接口地址
                filePath: canvas_temp_res.tempFilePath,
                name: 'file',
                formData: {},
                success(upload_res) {
                  // console.log(upload_res)
                  let json_upload_res = JSON.parse(upload_res.data)
                  // resolve(upload_res.data)
                  // console.log(json_upload_res)
                  if (json_upload_res.msg != "success") {
                    app.showTipMsg(res.msg)
                    reject()
                  } else {
                    resolve(json_upload_res.data)
                  }
                },
                fail(upload_err) {
                  // console.log(upload_err)
                  reject(upload_err)
                }
              })
            },
            fail(canvas_temp_err) {
              reject(canvas_temp_err)
            }
          })
        })
      })
    })
    return toTempPath
  },

  // 关闭分享遮罩层
  HideShareMask: function () {
    this.setData({
      TaskShow: 0
    })
    wx.showTabBar()
  },

  showSharePost: function () {
    const that = this
    let CarteInfo = this.data.CarteInfo
    CarteInfo.img.src = CarteInfo.img.src.split('?x-oss-process=style/index_mp')[0];
    CarteInfo.comLogo.src = CarteInfo.comLogo.src.split('?x-oss-process=style/goods_skeletonize')[0];
    wx.navigateTo({
      url: '/pages/sharePost/sharePost?carte_info=' + JSON.stringify(CarteInfo)
    })
  },

  // 打开雷达互动页面
  goRadarCenter: function () {
    const that = this
    wx.showLoading({
      mask: 'true'
    })
    wx.redirectTo({
      url: '/radarPages/radarCenter/radarCenter',
      success() {
        wx.hideLoading()
      },
      fail() {
        wx.hideLoading()
      }
    })
  },

  // 打开聊天列表页面
  goContactList: function () {
    const that = this
    wx.redirectTo({
      url: '/pages/contactList/contactList'
    })
  },

  // 返回名片首页
  goPerson: function () {
    const that = this
    wx.switchTab({
      url: '/pages/person/person',
    })
  },

  // 打开商品管理页面
  goManagePage: function () {
    const that = this
    if (that.data.CarteInfo.is_staff==1){
      app.showTipMsg('无权限')
    }else{
      wx.redirectTo({
        url: '/pages/manageGoods/manageGoods'
      })
    }
    
  },
  to_service:function(e){
    const that = this
    if (that.data.CarteInfo.is_staff == 1) {
      app.showTipMsg('无权限')
    } else {
      wx.navigateTo({
        url: e.currentTarget.dataset.url
      })
    }
  },

  // 打开名片编辑页面
  showEditCarte: function () {
    const that = this
    wx.navigateTo({
      url: '/pages/editCarte/editCarte'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    const that = this
    // const shareInfo = this.data.shareInfo
    // const carte = this.data.shareInfo.carte

    // console.log(e)
    // app.radarAdd(app.globalData.userInfo.id,3)
    var share_content = app.globalData.userInfo.share_content;
    if (e.from === 'button') {
      // 来自页面内转发按钮
    }
    var sharecontent = '';
    if (that.data.shareContent !== '') {
      sharecontent = that.data.shareContent
    } else {
      if (share_content != undefined) {
        if (share_content.indexOf("**") != -1) {
          sharecontent = share_content.replace('**', carte.name.content);
        } else {
          sharecontent = share_content
        }
      } else {
        sharecontent = app.globalData.userInfo.username;
      }
    }


    console.log(app.globalData.userInfo.id);
    return {
      title: sharecontent,
      path: '/pages/carteShow/carteShow?carte_id=' + app.globalData.userInfo.id + '&share_id=' + app.globalData.userInfo.id,
      // imageUrl: that.data.share_img.src,
      complete(res) {
        // console.log(res)
        that.setData({
          haveTap: 1,
          TaskShow: 0
        })
      }
    }
  }
})